<?php
namespace app\api\controller;

use app\admin\model\Config as ConfigModel;
use app\common\controller\AppCommon;
use common\Token;
use think\exception\HttpResponseException;
use think\facade\Db;
use think\facade\Filesystem;
use think\facade\Request;

class Common extends AppCommon
{
    protected $url = null;
    public function __construct(){
        parent::__construct();
        $this->url = Request::scheme().'://' . Request::host();
    }

    public function resJson(...$args){
        throw new HttpResponseException(resJson(...$args));
    }

    public function getToken()
    {
        $userData = [
            'user_id' => 3,
            'exp' => time() + 2592000
        ];
        $token = Token::getToken($userData);
        return resJson(200, 'ok', ['token' => $token]);
    }

    /**
     * 手机发送验证码
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getSmCode(){
        $mobile = input('param.mobile', '', 'trim');
        $type = input('param.type', 0, 'intval');
        if (empty($mobile) || !$type) return resJson(0,'缺失参数');
        $flag = '';
        switch ($type)
        {
            case 1:
                $flag = 'bind.';
                break;
        }
        $code = mt_rand(1000,9999);
        try{
            $send = sendSms($mobile,$type,['code' => $code]);
            if (!$send) {
                return resJson(0, '短信发送失败', '');
            }
            // 把短信记录到缓存;并设置失效时间
            cache($flag.$mobile,$code,300);
            return resJson(200, '短信发送成功');
        }catch (\Exception $e){
            return resJson(0, $e->getMessage());
        }
    }

    /**
     * 普通图片上传
     */
    public function uploadImg()
    {
        $file = request()->file('file');
        $data = getimagesize($file);
        if ($data == false) {
            return resjson(0, 'error');
        }
        try {
            $expArr = explode("/",$_FILES['file']['type']);
            $fileEx = strtoupper($expArr[1]);
            $allow = ['PNG','JPEG','JPG','GIF'];
            $checkEx = in_array($fileEx,$allow);
            if (!$checkEx){
                return resjson(1018, '图片不合法' );
            }
            $savename = Filesystem::disk('public')->putFile('images', $file, function () {
                return date('Ymd') . "/" . mt_rand(10, 90) . "/" . md5((string)microtime(true));
            });
            $data['data'] = '/uploads/' . $savename;
            return resjson(200, 'ok' ,$data['data']);
        } catch (\Exception $e) {
            return resjson(1010,  $e->getMessage());
        }
    }


    /**
     * IOS是否虚拟登录
     * @return \think\response\Json
     */
    public function isFalseLogin()
    {
        $info = ConfigModel::getCfgByModule('UPLOAD_IMG');
        return resJson(200,'ok',['status' => $info['false_login']]);
    }


    /**
     * 介绍
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function about(){
        $data = Db::name('page')->where('id',193)->field('id,title,qr_code,content')->find();
        return resJson(200,'ok',$data);
    }

    public function privacyAgreement(){
        $data = Db::name('page')->where('id',209)->field('content')->find();
        return resJson(200,'ok',$data);
    }

    public function registerAgreement(){
        $data = Db::name('page')->where('id',210)->field('content')->find();
        return resJson(200,'ok',$data);
    }

    /**
     * 话题状态
     * @return \think\response\Json
     */
    public function htStatus()
    {
        $info = ConfigModel::getCfgByModule('UPLOAD_IMG');
        return resJson(200,'ok',['status' => $info['ht_status']]);
    }


    /**
     * 服务协议
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function agreement(){
        $data = Db::name('page')->where('id',191)->field('id,title,content')->find();
        return resJson(200,'ok',$data);
    }


    /**
     * 隐私条款
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function privacy()
    {
        $data = Db::name('page')->where('id',192)->field('id,title,content')->find();
        return resJson(200,'ok',$data);
    }

    /**
     * 客服信息
     * @return \think\response\Json
     */
    public function customer()
    {
        $info = ConfigModel::getCfgByModule('UPLOAD_IMG');
        $info['kefu_qr'] = $this->url . $info['kefu_qr'];
        unset($info['file']);
        return resJson(200,'ok',$info);
    }

    /**
     * 过滤html标签
     */
    public function trimHtml($str, $start = 0, $end = 30, $isk = false) {
        if ($isk) {
            $length = strlen($str);
            if ($length > ($end-$start)){
                return mb_substr(str_replace('&nbsp;', '', strip_tags($str)), $start, $end, 'utf-8') . "...";
            }else{
                return mb_substr(str_replace('&nbsp;', '', strip_tags($str)), $start, $end, 'utf-8');
            }
        } else {
            return mb_substr(str_replace('&nbsp;', '', strip_tags($str)), $start, $end, 'utf-8');
        }
    }


    /**
     * 把时间戳转换成多少时间之前
     * @param $time
     * @return false|string
     */
    function wordTime($time) {
        $time = (int) substr($time, 0, 10);
        $int = time() - $time;
        if ($int <= 2){
            $str = sprintf('刚刚', $int);
        }elseif ($int < 60){
            $str = sprintf('%d秒前', $int);
        }elseif ($int < 3600){
            $str = sprintf('%d分钟前', floor($int / 60));
        }elseif ($int < 86400){
            $str = sprintf('%d小时前', floor($int / 3600));
        }elseif ($int < 2592000){
            $str = sprintf('%d天前', floor($int / 86400));
        }else{
            $str = date('Y-m-d', $time);
        }
        return $str;
    }
	
}
